package bmatch.tech.hello.resource;

import bmatch.tech.hello.auth.Jwtutil;
import bmatch.tech.hello.auth.TokenNeeded;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

/**
 * TokenNeededFilter的注释
 *
 * @author: Awake
 * @date: 2018-12-11 21:18
 **/
@TokenNeeded
@Priority(Priorities.AUTHENTICATION)
public class TokenNeededFilter implements ContainerRequestFilter {
    private static Logger log = LoggerFactory.getLogger(TokenNeededFilter.class);


    @Override
    public void filter(ContainerRequestContext requestContext) {
        // 从 header 取token信息
        String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
        // 从 cookie 取token信息
        if (authorizationHeader == null) {
            authorizationHeader = requestContext.getCookies().get("sid").getValue();
        }

        if (StringUtils.isBlank(authorizationHeader)) {
            requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
            return;
        }

        String token = authorizationHeader.substring("Bearer".length()).trim();

        try {
            //解析并传出userId
            String userId = Jwtutil.parse(token);
            requestContext.getHeaders().add("userId", userId);
        } catch (Exception e) {
            log.error("", e);
            requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
        }

    }
}
